/*
 * author      : 吴中勤
 * date        : 2019/3/13
 * description : TODO
 */

package org.wzq.learn;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class AppRuntimeEnv {
    private static final Logger logger = LoggerFactory.getLogger(AppRuntimeEnv.class);

    // xRequestId
    private ThreadLocal<String> xRequestId = new ThreadLocal() {
        protected String initialValue() {
            return null;
        }
    };

    public void setXRequestId(String xRequestId) {
        if (logger.isInfoEnabled()) logger.info("设置 xRequestId = " + xRequestId);
        this.xRequestId.set(xRequestId);
    }

    public String getXRequestId() {
        return this.xRequestId.get();
    }

    // 是否真实流量
    private ThreadLocal<Boolean> isMock = new ThreadLocal() {
        protected Boolean initialValue() {
            return Boolean.valueOf(false);
        }
    };

    public Boolean isMock() {
        return isMock.get();
    }

    public void setMock(Boolean isMock) {
        if (logger.isInfoEnabled()) logger.info("设置 isMock = " + isMock);
        this.isMock.set(isMock);
    }

    public void clean() {
        this.xRequestId.set(null);
        this.isMock.set(false);
    }

    private static class AppRuntimeEnvObj {
        private final String xRequestId;
        private final Boolean isMock;

        public AppRuntimeEnvObj(AppRuntimeEnv appRuntimeEnv) {
            this.xRequestId = appRuntimeEnv.getXRequestId();
            this.isMock = appRuntimeEnv.isMock();
        }
    }

    @Override
    public String toString() {
        AppRuntimeEnvObj appRuntimeEnvObj = new AppRuntimeEnvObj(this);
        return new Gson().toJson(appRuntimeEnvObj);
    }

    /** json string -> 对象 */
    public static <T> T jsonString2Obj(String json, Class<T> type) {
        if (null == json) return null;
        return new Gson().fromJson(json, type);
    }

    public static AppRuntimeEnv fromJson(String json) {
        AppRuntimeEnvObj obj = jsonString2Obj(json, AppRuntimeEnvObj.class);
        AppRuntimeEnv appRuntimeEnv = new AppRuntimeEnv();
        appRuntimeEnv.setMock(obj.isMock);
        appRuntimeEnv.setXRequestId(obj.xRequestId);
        return appRuntimeEnv;
    }
}
